<?php

namespace app\api\controller\xiluhouse;

use app\common\controller\Api;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * @title   预约订单管理
 * @desc    
 */
class Appoint extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['view_statistics'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    /**
     * @title  我的房源(经纪人)
     *
     */
    public function my_house_list()
    {
        $model = new \app\common\model\xiluhouse\HouseBroker;
        $map['house_broker.user_id'] = $this->auth->id;
        $map['house.status'] = 'normal';
        $map['user.status'] = 'normal';
        $map['house_broker.status'] = 'normal';

        $list = $model->with(['house', 'user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'profile'])->where($map)->where('profile.is_broker', 2)->order('id desc')->paginate();
        foreach ($list as $datas) {
            $datas->appendRelationAttr('house', ['house_tag_ids_text_arr']);
        }
        $this->success('', $list);
    }
    /**
     * @title 客户公海订单列表
     * @desc  
     *
     */
    public function appoint_log_list()
    {
        $model = new \app\common\model\xiluhouse\AppointLog;
        $list = $model
            ->with(['user'=>function($query){
                $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
            }])
            ->where('state', 1)
            ->where('rental_id', 0)
            ->where('user_id', 'neq', $this->auth->id)
            ->orderRaw('id desc')
            ->paginate();

        $this->success('', $list);
    }
    /**
     * @title 改变客户状态
     * @desc  从客户公海里添加入我的客户、放弃客户（订单回到客户公海）
     * @param int $id               无          id 
     * @param int $changeStatus      1          改变方式：1=从客户公海里添加入我的客户，2=放弃客户
     */
    public function change_appoint()
    {
        $id = $this->request->param('id/d', 0);
        if (!$id) {
            $this->error('参数错误');
        }
        $changeStatus = $this->request->param('changeStatus/d', 1);

        $model = new \app\common\model\xiluhouse\AppointLog;
        $info = $model->find($id);
        if (!$info) {
            $this->error('不存在改订单');
        }
        // 启动事务
        Db::startTrans();
        try {
            if ($changeStatus == 1) {
                // 从客户公海里添加入我的客户
                // 1、判断该客户是否已存在经纪人
                $usermodel = new \app\common\model\xiluhouse\UserProfile;
                $exist = $model->where('user_id', $info['user_id'])->where('state', 2)->where('is_using', 2)->find();
                if ($exist) {
                    $exist2 = $usermodel->where('user_id', $exist['broker_user_id'])->find();
                    if ($exist2) {
                        exception('该客户已存在经纪人');
                    }
                }
                $res = $model->change_appoint($info['user_id'], 1, $this->auth->id, $id);
                if (!$res) {
                    exception('提交失败，请稍后提交');
                }
            } else {
                $follow_model = new \app\common\model\xiluhouse\FollowLog;
                // 1、添加跟进记录
                $res = $follow_model->create([
                    'user_id' => $info['user_id'],
                    'broker_user_id' => $this->auth->id,
                    'appoint_log_id' => $id,
                    'house_state' => 6,
                    'name' => '咨询师放弃客户',
                ]);
                if (!$res) {
                    exception('提交失败，请稍后提交');
                }
                $res = $model->change_appoint($info['user_id'], 2, 0, $id);
                if (!$res) {
                    exception('提交失败，请稍后提交');
                }
            }
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('提交成功');
    }

    /**
     * @title 新增我的客户
     * @desc  新增我的客户
     * @param int $mobile               无          id
     * @param int $changeStatus      1          改变方式：1=从客户公海里添加入我的客户
     */
    public function create_appoint()
    {
        $mobile = $this->request->param('mobile', '');
        if (!$mobile) {
            $this->error('参数错误');
        }
        $user = \app\common\model\User::where('mobile',$mobile)->find();
        if(!$user){
            $this->error('手机号还未注册成为用户');
        }
        $changeStatus = $this->request->param('changeStatus/d', 1);

        $model = new \app\common\model\xiluhouse\AppointLog;

        $param['type'] = $this->request->param('type/d', 2);
        $param['subscribe_type'] = $this->request->param('subscribe_type/d', 0);
        $param['house_id'] = $this->request->param('house_id/d', 0);
        $param['broker_user_id'] = $this->request->param('broker_user_id/d', 0);
        $param['mobile'] = $this->request->param('mobile/s', '');
        $param['gender'] = $this->request->param('gender/d', 0);
        $param['view_date'] = $this->request->param('view_date/s', NULL);
        $param['min_total_price'] = $this->request->param('min_total_price/f', 0);
        $param['max_total_price'] = $this->request->param('max_total_price/f', 0);
        $param['prov'] = $this->request->param('prov/s', '');
        $param['city'] = $this->request->param('city/s', '');
        $param['region'] = $this->request->param('region/s', '');
        $param['orther_areas'] = $this->request->param('orther_areas/s', '');
        $param['remark'] = $this->request->param('remark/s', '');
        $param['house_search_roomnum_ids'] = $this->request->param('house_search_roomnum_ids/s', '');
        $param['user_id'] = $user->id;


        // 启动事务
        Db::startTrans();
        try {
            #1.添加到公海
            $result = $model->createNowLog($param);
            #拿到公海ID并加入到我的客户里面
            $info = $model;
            if (!$info) {
                $this->error('不存在改订单');
            }

            if ($changeStatus == 1) {
                // 从客户公海里添加入我的客户
                // 1、判断该客户是否已存在经纪人
                $usermodel = new \app\common\model\xiluhouse\UserProfile;
                $exist = $model->where('user_id', $info['user_id'])->where('state', 2)->where('is_using', 2)->find();
                if ($exist) {
                    $exist2 = $usermodel->where('user_id', $exist['broker_user_id'])->find();
                    if ($exist2) {
                        exception('该客户已存在经纪人');
                    }
                }
                $res = $model->change_appoint($info['user_id'], 1, $this->auth->id, $model->id);
                if (!$res) {
                    exception('提交失败，请稍后提交');
                }
            } else {
                $follow_model = new \app\common\model\xiluhouse\FollowLog;
                // 1、添加跟进记录
                $res = $follow_model->create([
                    'user_id' => $info['user_id'],
                    'broker_user_id' => $this->auth->id,
                    'appoint_log_id' => $id,
                    'house_state' => 6,
                    'name' => '咨询师放弃客户',
                ]);
                if (!$res) {
                    exception('提交失败，请稍后提交');
                }
                $res = $model->change_appoint($info['user_id'], 2, 0, $id);
                if (!$res) {
                    exception('提交失败，请稍后提交');
                }
            }
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('提交成功');
    }


    /**
     * @title 我的客户列表
     * @desc  
     * @param string $keyword          无     关键词
     * @param string $house_state      1     购房状态:1=待看房,2=已看房,3=已付订,4=已签约,5=已款清
     */
    public function my_user_list()
    {
        $keyword = $this->request->param('keyword/s', '');
        if ($keyword) {
            $map['appoint_log.mobile|user.nickname'] = ['like', '%' . $keyword . '%'];
        }
        $house_state = $this->request->param('house_state/d', 1);
        // 
        $map['appoint_log.house_state'] = $house_state;
        //日期条件
        if($date = $this->request->param('date')){
            $time1 = date('Y-m-01 00:00:00', strtotime($date));
            $time2 = date('Y-m-d 23:59:59', strtotime("$time1 +1 month -1 day"));
            if($house_state==1){
                $map['appoint_log.distributetime'] = ['between',[strtotime($time1),strtotime($time2)]];
            }else if($house_state == 2){
                $map['appoint_log.view_date'] = ['between',[$time1,$time2]];
            }
        }

        $model = new \app\common\model\xiluhouse\AppointLog;
        $list = $model
            ->with(['user'=>function($query){
                $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
            }])
            ->where('appoint_log.broker_user_id', $this->auth->id)
            ->where('appoint_log.state', 2)
            ->where('appoint_log.is_using', 2)
            ->where('appoint_log.rental_id', 0)
            ->where('appoint_log.user_id', 'neq', $this->auth->id)
            ->where($map)
            ->orderRaw('id desc')
            ->paginate();
        $followmodel = new \app\common\model\xiluhouse\FollowLog;
        $nowTime=time();
        foreach ($list as $key => $value) {
            $value->new_follow_text='';
            $value->followtime_text='刚刚维护';
            $value->append(['new_follow_text','followtime_text']);
            $exist=$followmodel->field('createtime,name')->where('user_id', $value['user_id'])->where('broker_user_id', $this->auth->id)->orderRaw('id desc')->find();
            if($exist){
                $cha=time_cha($nowTime,$exist->createtime);
                $value->followtime_text=$cha?$cha.'未维护':'刚刚维护';
                $value->new_follow_text=$exist->name;
            }
        }
        $this->success('', $list);
    }
    /**
     * @title 我的客户详情
     * @desc  
     * @param int $id          无        id 
     */
    public function my_user_detail()
    {
        $id = $this->request->param('id/d', 0);
        if (!$id) {
            $this->error('参数错误');
        }
        $model = new \app\common\model\xiluhouse\AppointLog;
        $info = $model->with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        },'userprofile'])->find($id);

        $followmodel = new \app\common\model\xiluhouse\FollowLog;
        $nowTime=time();
        $info->new_follow_text='';
        $info->followtime_text='刚刚维护';
        $info->append(['new_follow_text','followtime_text']);
        $exist=$followmodel->field('createtime,name')->where('user_id', $info['user_id'])->where('broker_user_id', $this->auth->id)->orderRaw('id desc')->find();
        if($exist){
            $cha=time_cha($nowTime,$exist->createtime);
            $info->followtime_text=$cha?$cha.'未维护':'刚刚维护';
            $info->new_follow_text=$exist->name;
        }

        $this->success('', $info);
    }
    /**
     * @title 跟进记录列表
     * @desc  
     * @param int $id          无        订单记录id 
     */
    public function follow_log_list()
    {
        $id = $this->request->param('id/d', 0);
        if (!$id) {
            $this->error('参数错误');
        }
        $model = new \app\common\model\xiluhouse\AppointLog;
        $info = $model->find($id);
        if (!$info) {
            $this->error('不存在该记录');
        }
        $model = new \app\common\model\xiluhouse\FollowLog;
        $list = $model
            ->where('user_id', $info['user_id'])
            ->where('broker_user_id', $this->auth->id)
            ->orderRaw('id desc')
            ->paginate();
        $this->success('', $list);
    }
    /**
     * @title 提交跟进记录
     * @desc  提交跟进记录
     *
     * @param int    $appoint_log_id           无     关联预约订单
     * @param int    $house_state              无     购房状态:0=无意向(已流失),1=待看房(已分配),2=已看房,3=已付订,4=已签约,5=已款清,6=放弃客户
     * @param string $name                     无     跟进标题
     * @param string $discription              无     详细描述
     * @param string $dissatisfaction          无     不满意的描述
     * @param string $images                  无     证明多图
     * @param string $money                   无     成交金额
     *
     */
    public function create_follow_log()
    {
        $params['appoint_log_id'] = $this->request->param('appoint_log_id/d', 0);
        $params['house_state'] = $this->request->param('house_state/d', 1);
        $params['name'] = $this->request->param('name/s', '');
        $params['discription'] = $this->request->param('discription/s', '');
        $params['dissatisfaction'] = $this->request->param('dissatisfaction/s', '');
        $params['images'] = $this->request->param('images/s', '');
        $params['money'] = $this->request->param('money/f', 0);
        if (!$params['appoint_log_id'] || !$params['name'] || !$params['discription']) {
            $this->error('参数错误');
        }
        $exist = \app\common\model\xiluhouse\AppointLog::find($params['appoint_log_id']);
        if (!$exist) {
            $this->error('参数错误');
        }
        if (!isset($exist['can_house_state_arr'][$params['house_state']])) {
            $this->error('购房状态错误');
        }
        $params['user_id'] = $exist['user_id'];
        $params['broker_user_id'] = $exist['broker_user_id'];
        // 启动事务
        Db::startTrans();
        try {
            $model = new \app\common\model\xiluhouse\FollowLog;
            $res = $model->createNowLog($params);
            if (!$res) {
                if ($err_msg = $model->nowError()) {
                    exception($err_msg);
                } else {
                    exception('提交失败，请稍后提交');
                }
            }
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('提交成功，请等待审核');
    }

    /**
     * @title 统计图数据
     * @desc  统计
     *
     * @param int    $appoint_log_id           无     关联预约订单
     *
     */
    public function statistics()
    {
        $appoint_log_id = $this->request->param('appoint_log_id/d', 0);
        if (!$appoint_log_id) {
            $this->error('参数错误');
        }
        $exist = \app\common\model\xiluhouse\AppointLog::with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }])->find($appoint_log_id);
        if (!$exist) {
            $this->error('参数错误');
        }
        $this->success('', $exist);
    }

    /**
     * @title 看房数量统计图
     * @desc  统计看房数量
     *
     * @param int    $appoint_log_id           无     关联预约订单
     * @param int    $day_type           1     多少天内的统计图：1=14天，2=30天（一个月）,3=90天（3个月），4=180天（6个月）
     * @param string     $city      上海市         所在城市
     * @return array   $view_count1   -    线上看房
     * @return array   $view_count1_2   -    本市平均线上看房
     * @return array   $view_count2   -    线下看房
     * @return array   $view_count2_2   -    本市平均线下看房
     */
    public function view_statistics()
    {
        $city = $this->request->request('city', '上海市');
        $appoint_log_id = $this->request->param('appoint_log_id/d', 0);
        if (!$appoint_log_id) {
            $this->error('参数错误');
        }
        $exist = \app\common\model\xiluhouse\AppointLog::find($appoint_log_id);
        if (!$exist) {
            $this->error('参数错误');
        }
        $day_type = $this->request->param('day_type/d', 1);
        $day_arr = [14, 30, 90, 180];
        $now_days = $day_arr[$day_type - 1];
 
        $house_view_db1 = Db::name('xiluhouse_house_view');
        $house_view_db1_2 = Db::name('xiluhouse_house_view');
        $house_view_db2 = Db::name('xiluhouse_follow_log');
        $house_view_db2_2 = Db::name('xiluhouse_follow_log');
        if ($day_type < 3) {
            $start_date = date('Y-m-d', strtotime('-' . $now_days . ' days'));
            $end_date = date('Y-m-d');
            $house_view_db1->field('FROM_UNIXTIME(createtime, "%Y-%m-%d") AS createdate');
            $house_view_db1_2->field('FROM_UNIXTIME(a.createtime, "%Y-%m-%d") AS createdate');
            $house_view_db2->field('FROM_UNIXTIME(createtime, "%Y-%m-%d") AS createdate');
            $house_view_db2_2->field('FROM_UNIXTIME(a.createtime, "%Y-%m-%d") AS createdate');
        } else if ($day_type == 3) {
            $start_date = date('Y-m-01', strtotime('-3 months'));
            $end_date = date('Y-m-31');
            $house_view_db1->field('FROM_UNIXTIME(createtime, "%Y-%m") AS createdate');
            $house_view_db1_2->field('FROM_UNIXTIME(a.createtime, "%Y-%m") AS createdate');
            $house_view_db2->field('FROM_UNIXTIME(createtime, "%Y-%m") AS createdate');
            $house_view_db2_2->field('FROM_UNIXTIME(a.createtime, "%Y-%m") AS createdate');
        } else {
            $start_date = date('Y-m-01', strtotime('-6 months'));
            $end_date = date('Y-m-31');
            $house_view_db1->field('FROM_UNIXTIME(createtime, "%Y-%m") AS createdate');
            $house_view_db1_2->field('FROM_UNIXTIME(a.createtime, "%Y-%m") AS createdate');
            $house_view_db2->field('FROM_UNIXTIME(createtime, "%Y-%m") AS createdate');
            $house_view_db2_2->field('FROM_UNIXTIME(a.createtime, "%Y-%m") AS createdate');
        }
        $starttime = strtotime($start_date);
        $endtime = strtotime($end_date);
        $viewList1 = $house_view_db1
            ->field('count(*) AS count1')
            ->where('user_id', $exist['user_id'])
            // ->where('status','normal')
            ->whereTime('createtime', 'between', [$start_date, $end_date])
            // ->where('deletetime','null')
            ->group('createdate')
            ->select();
        $viewList1_2 = $house_view_db1_2
            ->alias('a')
            ->join('xiluhouse_house b', 'b.id=a.house_id')
            ->field('count(*) AS count1_2,a.user_id AS now_user_id')
            ->where('b.city', $city)
            ->whereTime('a.createtime', 'between', [$start_date, $end_date])
            ->group('createdate,a.user_id')
            ->select();
        $viewList2 = $house_view_db2
            ->field('count(*) AS count2')
            ->where('user_id', $exist['user_id'])
            ->where('status', 'normal')
            ->whereTime('createtime', 'between', [$start_date, $end_date])
            ->where('house_state', 2)
            ->group('createdate')
            ->select();
        $viewList2_2 = $house_view_db2_2
            ->alias('a')
            ->join('xiluhouse_appoint_log b', 'b.id=a.appoint_log_id')
            ->field('count(*) AS count2_2,a.user_id AS now_user_id')
            ->where('b.city', $city)
            ->where('a.status', 'normal')
            ->whereTime('a.createtime', 'between', [$start_date, $end_date])
            ->where('a.house_state', 2)
            ->group('createdate,a.user_id')
            ->select();
        if ($day_type > 2) {
            //按月构造数据
            $starttime = strtotime('last month', $starttime);
            while (($starttime = strtotime('next month', $starttime)) <= $endtime) {
                $date_arr[] = date('Y-m', $starttime);
            }
        } else {
            //按天构造数据
            for ($time = $starttime; $time <= $endtime;) {
                $date_arr[] = date("Y-m-d", $time);
                $time += 86400;
            }
        }
        $list = array_fill_keys($date_arr, 0);
        $series = [
            'view_count1'   => [],
            'view_count1_2'   => [],
            'view_count2'   => [],
            'view_count2_2'   => [],
        ];
        $temp1 = $list;
        foreach ($viewList1 as $k => $v) {
            $temp1[$v['createdate']] = $v['count1'];
        }
        foreach ($temp1 as $k => $v) {
            $series['view_count1'][] = $v;
        }
        $arr1 = [];
        foreach ($viewList1_2 as $k => $v) {
            $arr1[$v['createdate']][] = $v['count1_2'];
        }
        $temp = $list;
        foreach ($arr1 as $k => $v) {
            $temp[$k] = count($v) == 0 ? 0 : round(array_sum($v) / count($v));
        }
        foreach ($temp as $k => $v) {
            $series['view_count1_2'][] = $v;
        }
        $temp = $list;
        foreach ($viewList2 as $k => $v) {
            $temp[$v['createdate']] = $v['count2'];
        }
        foreach ($temp as $k => $v) {
            $series['view_count2'][] = $v;
        }

        $arr2 = [];
        foreach ($viewList2_2 as $k => $v) {
            $arr2[$v['createdate']][] = $v['count2_2'];
        }
        $temp = $list;
        foreach ($arr2 as $k => $v) {
            $temp[$k] = count($v) == 0 ? 0 : round(array_sum($v) / count($v));
        }
        foreach ($temp as $k => $v) {
            $series['view_count2_2'][] = $v;
        }
        // foreach ($series as $k => &$v)
        // {
        //     $v = array_values($v);
        // }
        // unset($v);
        $this->success('', ['column' => $date_arr, 'series' => $series]);
    }
    /**
     * @title 价格统计图
     * @desc  统计价格
     *
     * @param int    $appoint_log_id           无     关联预约订单
     * @param int    $day_type           1     多少天内的统计图：1=14天，2=30天（一个月）,3=90天（3个月），4=180天（6个月）
     * @return array   $view_count1   -    均价
     */
    public function price_statistics()
    {
        $appoint_log_id = $this->request->param('appoint_log_id/d', 0);
        if (!$appoint_log_id) {
            $this->error('参数错误');
        }
        $exist = \app\common\model\xiluhouse\AppointLog::find($appoint_log_id);
        if (!$exist) {
            $this->error('参数错误');
        }
        $day_type = $this->request->param('day_type/d', 1);
        $day_arr = [14, 30, 90, 180];
        $now_days = $day_arr[$day_type - 1];

        $house_view_db1 = Db::name('xiluhouse_house_view');
        if ($day_type < 3) {
            $start_date = date('Y-m-d', strtotime('-' . $now_days . ' days'));
            $end_date = date('Y-m-d');
            $house_view_db1->field('FROM_UNIXTIME(a.createtime, "%Y-%m-%d") AS createdate');
        } else if ($day_type == 3) {
            $start_date = date('Y-m-01', strtotime('-3 months'));
            $end_date = date('Y-m-31');
            $house_view_db1->field('FROM_UNIXTIME(a.createtime, "%Y-%m") AS createdate');
        } else {
            $start_date = date('Y-m-01', strtotime('-6 months'));
            $end_date = date('Y-m-31');
            $house_view_db1->field('FROM_UNIXTIME(a.createtime, "%Y-%m") AS createdate');
        }
        $starttime = strtotime($start_date);
        $endtime = strtotime($end_date);
        $viewList1 = $house_view_db1
            ->alias('a')
            ->join('xiluhouse_house b', 'b.id=a.house_id')
            ->field('AVG(b.price) AS count1')
            ->where('a.user_id', $exist['user_id'])
            ->whereTime('a.createtime', 'between', [$start_date, $end_date])
            ->group('createdate')
            ->select();
        if ($day_type > 2) {
            //按月构造数据
            $starttime = strtotime('last month', $starttime);
            while (($starttime = strtotime('next month', $starttime)) <= $endtime) {
                $date_arr[] = date('Y-m', $starttime);
            }
        } else {
            //按天构造数据
            for ($time = $starttime; $time <= $endtime;) {
                $date_arr[] = date("Y-m-d", $time);
                $time += 86400;
            }
        }
        $list = array_fill_keys($date_arr, 0);
        $series = [
            'view_count1'   => [],
        ];
        $temp = $list;
        foreach ($viewList1 as $k => $v) {
            $temp[$v['createdate']] = $v['count1'];
        }
        foreach ($temp as $k => $v) {
            $series['view_count1'][] = $v;
        }

        foreach ($series as $k => &$v) {
            $v = array_values($v);
        }
        unset($v);
        $this->success('', ['column' => $date_arr, 'series' => $series]);
    }
    /**
     * @title 面积统计图
     * @desc  统计面积
     *
     * @param int    $appoint_log_id           无     关联预约订单
     * @param int    $day_type           1     多少天内的统计图：1=14天，2=30天（一个月）,3=90天（3个月），4=180天（6个月）
     * @return array   $view_count1   -    最大面积
     * @return array   $view_count2   -    最小面积
     */
    public function space_statistics()
    {
        $appoint_log_id = $this->request->param('appoint_log_id/d', 0);
        if (!$appoint_log_id) {
            $this->error('参数错误');
        }
        $exist = \app\common\model\xiluhouse\AppointLog::find($appoint_log_id);
        if (!$exist) {
            $this->error('参数错误');
        }
        $day_type = $this->request->param('day_type/d', 1);
        $day_arr = [14, 30, 90, 180];
        $now_days = $day_arr[$day_type - 1];

        $house_view_db1 = Db::name('xiluhouse_house_view');
        $house_view_db2 = Db::name('xiluhouse_house_view');
        if ($day_type < 3) {
            $start_date = date('Y-m-d', strtotime('-' . $now_days . ' days'));
            $end_date = date('Y-m-d');
            $house_view_db1->field('FROM_UNIXTIME(a.createtime, "%Y-%m-%d") AS createdate');
            $house_view_db2->field('FROM_UNIXTIME(a.createtime, "%Y-%m-%d") AS createdate');
        } else if ($day_type == 3) {
            $start_date = date('Y-m-01', strtotime('-3 months'));
            $end_date = date('Y-m-31');
            $house_view_db1->field('FROM_UNIXTIME(a.createtime, "%Y-%m") AS createdate');
            $house_view_db2->field('FROM_UNIXTIME(a.createtime, "%Y-%m") AS createdate');
        } else {
            $start_date = date('Y-m-01', strtotime('-6 months'));
            $end_date = date('Y-m-31');
            $house_view_db1->field('FROM_UNIXTIME(a.createtime, "%Y-%m") AS createdate');
            $house_view_db2->field('FROM_UNIXTIME(a.createtime, "%Y-%m") AS createdate');
        }
        $starttime = strtotime($start_date);
        $endtime = strtotime($end_date);
        $viewList1 = $house_view_db1
            ->alias('a')
            ->join('xiluhouse_house b', 'b.id=a.house_id')
            ->field('AVG(b.min_space) AS count1')
            ->where('a.user_id', $exist['user_id'])
            ->whereTime('a.createtime', 'between', [$start_date, $end_date])
            ->group('createdate')
            ->select();
        $viewList2 = $house_view_db2
            ->alias('a')
            ->join('xiluhouse_house b', 'b.id=a.house_id')
            ->field('AVG(b.max_space) AS count2')
            ->where('a.user_id', $exist['user_id'])
            ->whereTime('a.createtime', 'between', [$start_date, $end_date])
            ->group('createdate')
            ->select();
        if ($day_type > 2) {
            //按月构造数据
            $starttime = strtotime('last month', $starttime);
            while (($starttime = strtotime('next month', $starttime)) <= $endtime) {
                $date_arr[] = date('Y-m', $starttime);
            }
        } else {
            //按天构造数据
            for ($time = $starttime; $time <= $endtime;) {
                $date_arr[] = date("Y-m-d", $time);
                $time += 86400;
            }
        }
        $list = array_fill_keys($date_arr, 0);
        $series = [
            'view_count1'   => [],
            'view_count2'   => [],
        ];
        $temp = $list;
        foreach ($viewList1 as $k => $v) {
            $temp[$v['createdate']] = $v['count1'];
        }
        foreach ($temp as $k => $v) {
            $series['view_count1'][] = $v;
        }
        $temp = $list;
        foreach ($viewList2 as $k => $v) {
            $temp[$v['createdate']] = $v['count2'];
        }
        foreach ($temp as $k => $v) {
            $series['view_count2'][] = $v;
        }
        foreach ($series as $k => &$v) {
            $v = array_values($v);
        }
        unset($v);
        $this->success('', ['column' => $date_arr, 'series' => $series]);
    }
    /**
     * @title 楼盘分析统计
     * @desc  浏览楼盘分析
     *
     * @param int    $appoint_log_id           无     关联预约订单
     */
    public function house_statistics_list()
    {
        $appoint_log_id = $this->request->param('appoint_log_id/d', 0);
        if (!$appoint_log_id) {
            $this->error('参数错误');
        }
        $exist = \app\common\model\xiluhouse\AppointLog::find($appoint_log_id);
        if (!$exist) {
            $this->error('参数错误');
        }
        $house_view_model = new \app\common\model\xiluhouse\HouseView;
        $list = $house_view_model->with(['house'])
            ->field(['house.*', 'count(*) as view_count'])
            ->where('house.status', 'normal')
            ->where('house.deletetime', null)
            ->where('house_view.user_id', $exist['user_id'])
            ->group('house_id')
            ->order('view_count desc')
            ->paginate(5);
        foreach ($list as $key => $value) {
            $value->append(['collect_num']);
        }
        $this->success('', $list);
    }
    /**
     * @title 居室分析统计
     * @desc  浏览居室分析
     *
     * @param int    $appoint_log_id           无     关联预约订单
     */
    public function room_statistics_data()
    {
        $appoint_log_id = $this->request->param('appoint_log_id/d', 0);
        if (!$appoint_log_id) {
            $this->error('参数错误');
        }
        $exist = \app\common\model\xiluhouse\AppointLog::find($appoint_log_id);
        if (!$exist) {
            $this->error('参数错误');
        }
        $data = [];
        $house_view_model = new \app\common\model\xiluhouse\HouseView;
        $house_collect_model = new \app\common\model\xiluhouse\HouseCollect;
        // 一居室
        $view_count = $house_view_model->with(['house'])
            ->where('house.status', 'normal')
            ->where('house.deletetime', null)
            ->where('house_view.user_id', $exist['user_id'])
            ->where('house.min_room_num', 1)
            ->count();
        $collect_count = $house_collect_model->with(['house'])
            ->where('house.status', 'normal')
            ->where('house.deletetime', null)
            ->where('house_collect.user_id', $exist['user_id'])
            ->where('house.min_room_num', 1)
            ->count();
        $data[] = [
            'name' => '一居室',
            'view_count' => $view_count,
            'collect_count' => $collect_count,
        ];
        // 二居室
        $view_count = $house_view_model->with(['house'])
            ->where('house.status', 'normal')
            ->where('house.deletetime', null)
            ->where('house_view.user_id', $exist['user_id'])
            ->where('house.min_room_num', 'elt', 2)
            ->where('house.max_room_num', 'egt', 2)
            ->count();
        $collect_count = $house_collect_model->with(['house'])
            ->where('house.status', 'normal')
            ->where('house.deletetime', null)
            ->where('house_collect.user_id', $exist['user_id'])
            ->where('house.min_room_num', 'elt', 3)
            ->where('house.max_room_num', 'egt', 3)
            ->count();
        $data[] = [
            'name' => '二居室',
            'view_count' => $view_count,
            'collect_count' => $collect_count,
        ];
        // 三居室
        $view_count = $house_view_model->with(['house'])
            ->where('house.status', 'normal')
            ->where('house.deletetime', null)
            ->where('house_view.user_id', $exist['user_id'])
            ->where('house.min_room_num', 'elt', 3)
            ->where('house.max_room_num', 'egt', 3)
            ->count();
        $collect_count = $house_collect_model->with(['house'])
            ->where('house.status', 'normal')
            ->where('house.deletetime', null)
            ->where('house_collect.user_id', $exist['user_id'])
            ->where('house.min_room_num', 'elt', 3)
            ->where('house.max_room_num', 'egt', 3)
            ->count();
        $data[] = [
            'name' => '三居室',
            'view_count' => $view_count,
            'collect_count' => $collect_count,
        ];
        // 四居室
        $view_count = $house_view_model->with(['house'])
            ->where('house.status', 'normal')
            ->where('house.deletetime', null)
            ->where('house_view.user_id', $exist['user_id'])
            ->where('house.min_room_num', 'elt', 4)
            ->where('house.max_room_num', 'egt', 4)
            ->count();
        $collect_count = $house_collect_model->with(['house'])
            ->where('house.status', 'normal')
            ->where('house.deletetime', null)
            ->where('house_collect.user_id', $exist['user_id'])
            ->where('house.min_room_num', 'elt', 4)
            ->where('house.max_room_num', 'egt', 4)
            ->count();
        $data[] = [
            'name' => '四居室',
            'view_count' => $view_count,
            'collect_count' => $collect_count,
        ];
        // 五室及以上
        $view_count = $house_view_model->with(['house'])
            ->where('house.status', 'normal')
            ->where('house.deletetime', null)
            ->where('house_view.user_id', $exist['user_id'])
            ->where('house.max_room_num', 'egt', 5)
            ->count();
        $collect_count = $house_collect_model->with(['house'])
            ->where('house.status', 'normal')
            ->where('house.deletetime', null)
            ->where('house_collect.user_id', $exist['user_id'])
            ->where('house.max_room_num', 'egt', 5)
            ->count();
        $data[] = [
            'name' => '五室及以上',
            'view_count' => $view_count,
            'collect_count' => $collect_count,
        ];
        $this->success('', $data);
    }
}
